import { forwardRef, useEffect, useState, useMemo, useImperativeHandle } from 'react';
import { DatePicker } from 'antd-mobile';
import moment from 'moment';
import { Field } from '@formily/core';
import { connect, mapProps, useField } from '@formily/react';
import { InbizIcon, useEvents } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { defaultProps } from '../../designer/schema';
import api from '../web/api';
import './index.less';
import delIcon from '@assets/ic-delete-circle.svg'
type IProps = {
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  value?: any;
  onChange?: any;
  emit?: () => void;
  readOnly?: boolean;
  disabled?: boolean;
  selectTitle: string;
  viewMode?:string;
} & typeof defaultProps;
type DateMode = 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second';

const EformDatePicker = forwardRef((props: IProps, ref: any) => {
  // 基础数据
  const { value, allowBeforeNow, min, max, viewMode } = props;
  const field = useField<Field>();
  const [visibly, setVisibly] = useState(false);
  const [minDate, setMinDate] = useState<undefined | Date>();
  const [maxDate, setMaxDate] = useState<undefined | Date>();
  const nowDate = useMemo(() => new Date(), []);
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props),
    }),
    [props.value],
  );

  useEffect(() => {
    // 验证是否满足 允许小于当前时间，最小值，最大值
    field.setValidatorRule('validator', (value: Date, rule: any, ctx: any) => {
      const format = ctx.field.componentProps.format;
      // 是否允许小于当前时间
      if (!ctx.field.componentProps.allowBeforeNow) {
        if (value && moment(value) < moment().startOf('day')) {
          // return getMessage('EformDatePicker.validate.DateNotAllowSmallThanNow');
          return <TextWidget>EformDatePicker.validate.DateNotAllowSmallThanNow</TextWidget>;
        }
      }
      const validValue = [
        {
          indexV: 's',
          accurate: 'second',
          format: 'YYYY-MM-DD HH:mm:ss',
        },
        {
          indexV: 'm',
          accurate: 'minute',
          format: 'YYYY-MM-DD HH:mm',
        },
        {
          indexV: 'H',
          accurate: 'hour',
          format: 'YYYY-MM-DD HH',
        },
        {
          indexV: 'D',
          accurate: 'day',
          format: 'YYYY-MM-DD',
        },
        {
          indexV: 'M',
          accurate: 'month',
          format: 'YYYY-MM',
        },
        {
          indexV: 'Y',
          accurate: 'year',
          format: 'YYYY',
        },
      ];
      // 最小值
      if (value && ctx.field.componentProps.min) {
        for (let i = 0; i < validValue.length; i++) {
          if (format?.indexOf(validValue[i].indexV) != -1) {
            if (
              moment(value) <
              moment(ctx.field.componentProps.min).startOf(validValue[i].accurate as any)
            ) {
              // return (
              //   getMessage('EformDatePicker.validate.dateCannotLessThan') +
              //   moment(ctx.field.componentProps.min).format(props.format)
              // );
              return (
                <>
                  <TextWidget>EformDatePicker.validate.dateCannotLessThan</TextWidget>
                  {moment(ctx.field.componentProps.min).format(props.format)}
                </>
              );
            }
          }
        }
      }
      // 最大值
      if (value && ctx.field.componentProps.max) {
        for (let i = 0; i < validValue.length; i++) {
          if (format?.indexOf(validValue[i].indexV) != -1) {
            if (
              moment(value) >
              moment(ctx.field.componentProps.max).endOf(validValue[i].accurate as any)
            ) {
              // return (
              //   getMessage('EformDatePicker.validate.dateCannotMoreThan') +
              //   moment(ctx.field.componentProps.max).format(props.format)
              // );
              return (
                <>
                  <TextWidget>EformDatePicker.validate.dateCannotMoreThan</TextWidget>
                  {moment(ctx.field.componentProps.max).format(props.format)}
                </>
              );
            }
          }
        }
      }
      return true;
    });

    // 根据最小最大值调整时间选择器的范围
    // console.log(moment(min).toDate(),moment(max).toDate());
    if (!min) {
      setMinDate(moment().subtract(30, 'y').toDate());
    } else {
      // if(){
      // }else{
      setMinDate(new Date(new Date(min).toDateString()));
      // }
    }
    if (!max) {
      setMaxDate(moment().add(30, 'y').toDate());
    } else {
      setMaxDate(moment(max).hour(23).minutes(59).second(59).toDate());
    }
  }, []);
  // 精度
  const mode: DateMode = useMemo(() => {
    switch (true) {
      case props.format.includes('s'):
        return 'second';
      case props.format.includes('m'):
        return 'minute';
      case props.format.includes('h'):
        return 'hour';
      case props.format.includes('D'):
        return 'day';
      case props.format.includes('M'):
        return 'month';
      case props.format.includes('Y'):
        return 'year';
      default:
        return 'day';
    }
  }, [props.format]);
  return (
    <>
      {viewMode == 'look' ? <div style={{fontSize:'16px'}}>{value? moment(props.value).format(props.format) : '' }</div>: <div
        onClick={
          props.readOnly
            ? () => { }
            : () => {
              setVisibly(true);
            }
        }
        className={'mobileEformSwitch divBtn'}
        style={{
          border: 'none',
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between',
          fontSize: '16px',
          padding: 0,
        }}
      >
        <DatePicker
          // {...other}
          title={props.selectTitle}
          min={allowBeforeNow ? minDate : nowDate}
          max={maxDate}
          defaultValue={new Date()}
          visible={visibly}
          onClose={() => {
            setVisibly(false);
          }}
          cancelText={<TextWidget>EformDatePicker.cancle</TextWidget>}
          confirmText={<TextWidget>EformDatePicker.ok</TextWidget>}
          onConfirm={(value: Date) => {
            props.onChange(value);
            // props.emit?.('onChange', moment(value).format(format));
            // $state((state: any) => ({ ...state, value: value }));
            // valideRef.current?.clear();
          }}
          precision={mode}
        >
          {() => {
            if (!value) {
              return (
                <div
                  style={props.readOnly ? {
                    width: '80px',
                    height: '25px'
                  } : { color: '#CCC' }}
                >
                  {!props.readOnly && props.placeholder}
                </div>
              );
            } else {
              return (
                <div
                  className={`${props.readOnly ? 'disable' : ''}`}
                  style={{ color: 'var(--inbiz-color-text)' }}
                >
                  {moment(value).format(props.format)}
                </div>
              );
            }
          }}
        </DatePicker>

        {props.value ?
          !props.readOnly && <div className='rightImg'>
            <img src={delIcon} alt="" className='icon' onClick={(e) => {
              props.onChange(null)
              e.preventDefault()
              e.stopPropagation()
            }} />
            <InbizIcon type="icon-ic-arrow-right-bold" />
          </div> :
          !props.readOnly && <div className='rightImg'>
            <InbizIcon type="icon-ic-arrow-right-bold" />
          </div>
        }

      </div>
      }
    </>
  );
});

(
  EformDatePicker as typeof EformDatePicker & IDefaultValueFormat<typeof defaultProps>
).originValueFormat = (value: any, props: object) => {
  return value && new Date(value);
};
(
  EformDatePicker as typeof EformDatePicker & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props): null | Date | void => {
  if (props.defaultValueType == 'customDefaultValue') {
    if (props.customDefaultValue) {
      return new Date(props.customDefaultValue);
    } else {
      return null;
    }
  } else {
    if (props.variableDefaultValue == 'nowTime') {
      return new Date();
    }
  }
};

export default connect(
  EformDatePicker,
  mapProps({}, (props, field) => {
    // field.decoratorProps.addonAfter = props.addonAfter;
    const others = props;
    others.placeholder = getMessage(props.placeholder);
    return { ...props };
  }),
);
